import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import store from '../store/index.js'
import mitt from '@/utils/mitt.js'
import { ElMessage } from 'element-plus'
const chat = TencentCloudChat.create({
	SDKAppID:import.meta.env.MODE=='cardlumi' ?20021380:20021380,
});

chat.registerPlugin({
	'tim-upload-plugin': TIMUploadPlugin
});
let userId = localStorage.getItem('info') && localStorage.getItem('info').merchNo
let isLogin = false


export default {


	// 获取用户在线状态

	getUserStatus(userIDList) {
		// 查询其他用户的状态
		let promise = chat.getUserStatus({
			userIDList: userIDList
		});
		promise.then(function (imResponse) {
			const {
				successUserList,
				failureUserList
			} = imResponse.data;
			// 查询成功的用户列表
			successUserList.forEach((item) => {
				const {
					userID,
					statusType,
					customStatus
				} = item;
				console.log(item, '用户状态')
				// userID - 用户 ID
				// statusType - 用户状态，枚举值及说明如下：
				// TencentCloudChat.TYPES.USER_STATUS_UNKNOWN - 未知
				// TencentCloudChat.TYPES.USER_STATUS_ONLINE - 在线
				// TencentCloudChat.TYPES.USER_STATUS_OFFLINE - 离线
				// TencentCloudChat.TYPES.USER_STATUS_UNLOGINED - 未登录
				// customStatus - 用户自定义状态
			});

			// 查询失败的用户列表
			failureUserList.forEach((item) => {
				const {
					userID,
					code,
					message
				} = item;
				// userID - 查询失败的用户 ID
				// code - 查询失败的错误码
				// message - 查询失败的错误信息
			});
		}).catch(function (imError) {
			console.warn('getUserStatus error:', imError); // 获取用户状态失败的相关信息
		});


	},

	// 登出
	onLoginOut() {
		let promise = chat.logout();
		promise.then(function (imResponse) {
			store.commit('user/imLogimChange',false)
			console.log(imResponse.data, 'im退出登录'); // 登出成功
		}).catch(function (imError) {
			console.warn('logout error:', imError);
		});

		// let promise = chat.destroy();
	},
	onDelete(conversationID) {
		let promise = chat.deleteConversation(conversationID);
		promise.then(function (imResponse) {
			// 删除会话成功
			const {
				conversationID
			} = imResponse.data; // 被删除的会话 ID
		}).catch(function (imError) {
			console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
		});

	},

	onRead(conversationID) {
		let promise = chat.setMessageRead({
			conversationID,
		});
		promise.then(function (imResponse) {
			console.log('已读上报成功')
			// 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
		}).catch(function (imError) {
			// 已读上报失败
			console.warn('setMessageRead error:', imError);
		});

	},
	revokeMessage(message){
		let promise = chat.revokeMessage(message);
   promise.then(function(imResponse) {
  // 消息撤回成功
  console.log('撤回成功')
      }).catch(function(imError) {
  // 消息撤回失败
         console.warn('revokeMessage error:', imError);
     });

	},
	sendMsg(data) {
		let isGetFirst = data.isGetFirst
		console.log('发送消息', data)
		let message = ''
		if (data.type == 'MSG_TEXT') {
			message = chat.createTextMessage({
				to: data.toUser,
				type: data.type,
				conversationType: data.conversationType,
				payload: {
					text: data.text
				},
				conversationID: data.conversationID,
				conversationType: data.conversationType,
				// 如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
				needReadReceipt: true
			});
		} else if (data.type == 'MSG_CUSTOM') {
			console.log('自定义', data)
			message = chat.createCustomMessage({
				to: data.toUser,
				conversationType: data.conversationType,
				payload: {
					data: data.text,
					description: data.description,
					extension: data.extension
				},
				cloudCustomData: '这是自定义'
			})
		} else {
			console.log('数据', data)
			message = chat.createImageMessage({
				to: data.toUser,
				type: data.type,
				conversationType: data.conversationType,
				payload: {
					file: data.file
				},
				conversationID: data.conversationID,
				conversationType: data.conversationType,
				// 如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
				needReadReceipt: true,
				onProgress: function (event) {
					console.log('file uploading:', event)
				}
			});
		}
		let promise = chat.sendMessage(message);
		promise.then(function (imResponse) {
			console.log(imResponse)
			// 发送成功
			console.log('发送成功');
			if(isGetFirst){
				mitt.emit('getFirstMsgList')
			}
			
		}).catch(function (imError) {
			// uni.$emit('sendErr', data)
			// 发送失败
			if(imError.code==20007){
				ElMessage({
					message: 'It has been blocked',
					type: 'error',
				})
			}
			console.warn('sendMessage error:', imError);
		});

	},
	clearChat (userId){
		let promise = chat.deleteConversation({conversationIDList: [`C2C${userId}`], clearHistoryMessage: true});
		promise.then(function(imResponse) {
		  // 删除会话成功
		  const { conversationIDList } = imResponse.data; // 被删除的会话 ID 列表
		}).catch(function(imError) {
		  console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
		})
		
	},

	getMessageList(type, userId) {
		// console.log(type,userId,999)
		let nextId = localStorage.getItem('nextReqMessageID') || ''
		if (type == 'first') {
			nextId = ''
		}
		// const store = msgStore()
		//非首次获取消息列表

		let promiseMsg = chat.getMessageList({
			conversationID: `C2C${userId}`,
			nextReqMessageID: nextId
		});

		promiseMsg.then(function (imResponse, nextId) {
			const messageList = imResponse.data.messageList; // 消息列表。
			const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
			const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
			console.log('消息列表', messageList)
			console.log('续拉id', nextReqMessageID)
			console.log('是否拉完', isCompleted)
			localStorage.setItem('nextReqMessageID', nextReqMessageID)
			if (type == 'first') {
				store.commit('user/setMsg', {
					messageList,
					isCompleted
				})
			} else {
				store.commit('user/pushMsg', {
					messageList,
					isCompleted
				})
			}
		});


		// };


	},
	loginIm(userInfo) {
            // console.log('login',userInfo)
		if (typeof (userInfo) == 'string') {
			userInfo = JSON.parse(userInfo)
		}
		console.log('开始登录', userInfo)
		if(!userInfo.username||!userInfo.userSig) return
		let promise = chat.login({
			userID: 'PI_' + userInfo.username,
			userSig: userInfo.userSig
		});

		promise.then(function (imResponse) {
			console.log('登录成功'); // 登录成功
			
			if (imResponse.data.repeatLogin === true) {
				// 标识账号已登录，本次登录操作为重复登录。
				console.log('重复登录');
			}
		}).catch(function (imError) {
			console.warn('login error:', imError); // 登录失败的相关信息
		});

		// chat.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
		chat.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
		let onSdkReady = function (event) {
			console.log('监听sdkready',)
			store.commit('user/imLogimChange',true)
		};
		chat.on(TencentCloudChat.EVENT.SDK_READY, onSdkReady);

		let onSdkNotReady = function (event) {
			console.log('监听', 'onSdkNotReady')
			// chat.login({userID: 'your userID', userSig: 'your userSig'});
		};
		chat.on(TencentCloudChat.EVENT.SDK_NOT_READY, onSdkNotReady);

		let onMessageReceived = function (event) {
			console.log('监听聊天记录更新', event)
			store.commit('user/setAddMsgList', event)
			mitt.emit('newMsg', event)

			// event.data - 存储 Message 对象的数组 - [Message]
		};
		chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
		// let onMessageModified = function(event) {
		// 	console.log('监听', 'onMessageModified')
		// 	// event.data - 存储被修改过的 Message 对象的数组 - [Message]
		// };
		// chat.on(TencentCloudChat.EVENT.MESSAGE_MODIFIED, onMessageModified);
		// let onMessageRevoked = function(event) {
		// 	console.log('监听', 'onMessageRevoked')
		// 	// event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isRevoked 属性值为 true
		// };
		// chat.on(TencentCloudChat.EVENT.MESSAGE_REVOKED, onMessageRevoked);
		let onMessageReadByPeer = function (event) {

			console.log('监听SDK 收到对端已读消息的通知，消息接收方调用 setMessageRead 已读上报成功后消息发送方会收到此事件。', 'onMessageReadByPeer')
			// event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isPeerRead 属性值为 true
			console.log(event)
		
			store.commit('user/readList', event.data)
			mitt.emit('readChange',event.data)//新
			// uni.$emit('changRead', event.data)
		};
		chat.on(TencentCloudChat.EVENT.MESSAGE_READ_BY_PEER, onMessageReadByPeer);

		let onMessageReadReceiptReceived = function (event) {
			console.log('监听', 'SDK 收到了消息的已读回执通知，消息接收方调用 sendMessageReadReceipt 时消息发送方会收到此事件。')
			// event.data - 存储消息已读回执信息的数组
			const readReceiptInfoList = event.data;
			readReceiptInfoList.forEach((item) => {
				const {
					groupID,
					userID,
					messageID,
					readCount,
					unreadCount,
					isPeerRead
				} = item;
				// messageID - 消息 ID
				// userID - C2C 消息接收方
				// isPeerRead - C2C 消息对端是否已读
				// groupID - 群组 ID
				// readCount - 群消息已读人数
				// unreadCount - 群消息未读人数
				const message = chat.findMessage(messageID);
				if (message) {
					if (message.conversationType === TencentCloudChat.TYPES.CONV_C2C) {
						if (message.readReceiptInfo.isPeerRead === true) {
							// 对端已读
							console.log('对端一度')
						}
					} else if (message.conversationType === TencentCloudChat.TYPES.CONV_GROUP) {
						if (message.readReceiptInfo.unreadCount === 0) {
							// 全部已读
							console.log('全部已读')
						} else {
							// message.readReceiptInfo.readCount - 消息最新的已读数
							// 如果想要查询哪些群成员已读了此消息，请使用 [getGroupMessageReadMemberList] 接口
						}
					}
				}
			});
		}
		chat.on(TencentCloudChat.EVENT.MESSAGE_READ_RECEIPT_RECEIVED, onMessageReadReceiptReceived);

		let onConversationListUpdated = function (event) {
			console.log('监听', '会话列表更新，event.data 是包含 Conversation 对象的数组。', event.data)

			store.commit('user/setConversationList', event.data)
		};
		chat.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, onConversationListUpdated);

		let onTotalUnreadMessageCountUpdated = function (event) {
			console.log('监听', '当前单聊和群聊会话的未读总数')
		};
		chat.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onTotalUnreadMessageCountUpdated);
		let onConversationInGroupUpdated = function (event) {
			console.log('监听', '会话分组内的会话更新时触发（如添加会话到分组，或者从分组内删除会话）。')
			const {
				groupName,
				conversationList
			} = event.data;
			// groupName - 会话分组名
			// conversationList - 分组内的会话列表
		}
		chat.on(TencentCloudChat.EVENT.CONVERSATION_IN_GROUP_UPDATED, onConversationInGroupUpdated);


		let onKickedOut = function (event) {

			console.log('监听非正常退出', event.data.type);
			// TencentCloudChat.TYPES.KICKED_OUT_MULT_ACCOUNT(Web端，同一账号，多页面登录被踢)
			// TencentCloudChat.TYPES.KICKED_OUT_MULT_DEVICE(同一账号，多端登录被踢)
			// TencentCloudChat.TYPES.KICKED_OUT_USERSIG_EXPIRED(签名过期)
			// TencentCloudChat.TYPES.KICKED_OUT_REST_API(REST API kick 接口踢出)
		};
		chat.on(TencentCloudChat.EVENT.KICKED_OUT, onKickedOut);
	}
}